package lt.inkredibl.iit.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import lt.inkredibl.iit.FileChooserSource;
import lt.inkredibl.iit.IITCFileFilter;
import lt.inkredibl.iit.ImgComponent;

@SuppressWarnings("serial")
public class ActLoad
	extends AbstractAction
{
	private ImgComponent _ic;
	private FileChooserSource _fcs = FileChooserSource.inst();
	private FileFilter _fileFilter = IITCFileFilter.inst();

	protected ActLoad(ImgComponent ic)
	{
		_ic = ic;
		putValue(Action.NAME, "Load...");
		putValue(Action.MNEMONIC_KEY, KeyEvent.VK_L);
	}
	
	public static ActLoad inst(ImgComponent ic)
	{
		return new ActLoad(ic);
	}

	public void actionPerformed(ActionEvent e)
	{
		JFileChooser fc = makeFileChooser();
		if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(null))
		{
			File f = fc.getSelectedFile();
			if (f != null)
			{
				try
				{
					FileInputStream in = new FileInputStream(f);
					Properties p = new Properties();
					p.load(in);
					_ic.setState(p);
				}
				catch (IOException xc)
				{
					JOptionPane.showMessageDialog(sourceToComponent(e),
					    xc.getMessage(),
					    xc.getClass().getName(),
					    JOptionPane.ERROR_MESSAGE);;
				}
			}
		}
	}

	private Component sourceToComponent(ActionEvent e)
	{
		return e.getSource() instanceof Component ? (Component)e.getSource() : null;
	}

	private JFileChooser makeFileChooser()
	{
		JFileChooser fc = _fcs.getFileChooser();
		fc.setDialogType(JFileChooser.OPEN_DIALOG);
		fc.setFileFilter(_fileFilter );
		return fc;
	}


}
